package com.xiaokai.config;

import com.xiaokai.model.SignatureUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.TreeMap;

/**
 * Author:yang
 * Date:2024-12-17 17:18
 * Description:验签
 */
@Component
@Slf4j
public class SignatureInterceptor implements HandlerInterceptor {

    @Value("${middlewares.appId}")
    private String MiddlewareAppId;

    @Value("${middlewares.appSecret}")
    private String MiddlewareAppSecret;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求参数
        String appId = request.getParameter("appId");
        String sign = request.getParameter("sign");
        String timestamp = request.getParameter("timestamp");
        String data = request.getParameter("data"); // 不存在时为null

        // 验证参数是否完整
        if (appId == null || sign == null || timestamp == null) {
            log.warn("appId: {}, sign: {}, timestamp: {}, data: {} 携带数据不完整", appId, sign, timestamp, data);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "请求携带的参数不完整");
            return false;
        }

        // 构建参数
        TreeMap<String, String> params = new TreeMap<>();
        params.put("appId", MiddlewareAppId);
        params.put("timestamp", timestamp);
        if (data != null && !data.isEmpty()){
            params.put("data", data);
        }

         //比对签名
        if (!SignatureUtils.verifySignature(MiddlewareAppSecret,sign, params)) {
            log.warn("appId: {}, sign: {}, timestamp: {}, data: {} 验证签名失败", appId, sign, timestamp, data);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "签名验证失败");
            return false;
        }

        request.setAttribute("data", data);

        return true;
    }

}
